import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import SettingMer from '@/utils/settingMer'
import { isPhone } from "@/libs/wechat";
// create an axios instance
// 清除可能缓存的旧API地址，使用新的配置
window.localStorage.removeItem("apiBaseURL");
window.localStorage.setItem("apiBaseURL", SettingMer.apiBaseURL);
const service = axios.create({
  
  baseURL: SettingMer.apiBaseURL, // 直接使用SettingMer中的配置，不使用localStorage
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000, // request timeout
  responseType: 'json',
  responseEncoding: 'utf8'
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log('发送请求:', {
      url: config.baseURL + config.url,
      method: config.method,
      data: config.data,
      params: config.params
    })
    
    // Token认证已移除
    if(/get/i.test(config.method)){
      config.params = config.params || {}
      config.params.temp= Date.parse(new Date()) / 1000
    }
    return config
  },
  error => {
    // do something with request error
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log('收到响应:', {
      url: response.config.url,
      status: response.status,
      data: response.data
    })
    
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 401) {
      // to re-login
      MessageBox.confirm('登录状态已过期，请重新登录。', '提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'light-green-btn',
        customClass:'tipClass'
      }).then(() => {
        // store.dispatch('user/resetToken').then(() => {
          location.reload()
        // })
      })
    }
    
    if (res.code === 40006) {
      return Promise.reject(res)
    }
    if (res.code === 40005) {
      return Promise.reject(res)
    }
    if (res.code !== 200  && res.code !== 401) {
      if (isPhone()) { //移动端
        return Promise.reject(res.message)
      }
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject()
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      // return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // 处理ApiResult包装的响应
      if (res.data !== undefined) {
        return res.data
      } else if (res.code === 200) {
        return res.data || res
      } else {
        return res
      }
    }
  },
  error => {
    console.error('请求错误详情:', {
      message: error.message,
      code: error.code,
      response: error.response,
      config: error.config
    })
    
    let errorMessage = '请求失败'
    if (error.response) {
      // 服务器响应了错误状态码
      const status = error.response.status
      const data = error.response.data
      
      switch (status) {
        case 404:
          errorMessage = '接口不存在，请检查后端服务是否正常运行'
          break
        case 500:
          errorMessage = '服务器内部错误，请稍后重试'
          break
        case 502:
          errorMessage = '网关错误，后端服务可能未启动'
          break
        case 503:
          errorMessage = '服务不可用，请稍后重试'
          break
        default:
          if (data && data.message) {
            errorMessage = data.message
          } else if (data && data.msg) {
            errorMessage = data.msg
          } else {
            errorMessage = '请求失败 (' + status + ')'
          }
      }
    } else if (error.code === 'ECONNREFUSED') {
      errorMessage = '无法连接到服务器，请检查后端服务是否启动'
    } else if (error.code === 'NETWORK_ERROR') {
      errorMessage = '网络错误，请检查网络连接'
    } else if (error.message) {
      errorMessage = error.message
    }
    
    Message({
      message: errorMessage,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service